from contextlib import asynccontextmanager
from datetime import datetime
from urllib.request import Request

from core.config import get_config, init_app_config

"""
    初始化系统参数,全局单例，初始化一定要放在导入其他模块之前
"""
app_config = init_app_config()

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from db.session import get_db
from core.log import setup_logging

logger = setup_logging("INFO")


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动前执行的代码
    yield  # 应用继续运行
    # 应用启动关闭前执行的代码
    print("应用关闭中...")


app = FastAPI(lifespan=lifespan)


# 定义中间件
@app.middleware("http")
async def log_request_time(request: Request, call_next):
    logger.info(f"{request.method} {request.url} ")
    # 继续处理请求
    response = await call_next(request)
    return response


@app.get("/")
async def root(db: Session = Depends(get_db)):
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


if __name__ == '__main__':
    import uvicorn

    # "main:app" 与 直接传入app对象是有区别的，启动机制不同
    # 传入main:app，uvicorn日志才能写入文件
    uvicorn.run("main:app", host=get_config("app.host"), port=get_config("app.port"),
                log_level=get_config("app.log_level", "info"))
